﻿#include "FilaPowerForm.h"
#include "ui_FilaPowerForm.h"
#include <QMouseEvent>
#include "common/Utils.h"
#include <QTimer>
#include <QMessageBox>

FilaPowerForm::FilaPowerForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FilaPowerForm),bEleCurSetOnlyWrite(false),bEleCurEditing(false),
    SwtichOffIcon(":/res/image/SwtichOff.png"),SwtichOnIcon(":/res/image/SwtichOn.png"),
    bConnectionState(false)
{
    ui->setupUi(this);

    /*******************通信线程的设置***********************************/
    m_Thread = new QThread();
    m_ModBusTcpWorker = new ModBusTcpWorker(nullptr);

    // 将 worker 移动到新线程，并确保在线程结束时删除
    m_ModBusTcpWorker->moveToThread(m_Thread);
    connect(m_Thread, &QThread::finished, m_Thread, &QObject::deleteLater);

    // 当 worker 被删除时，结束线程
    connect(m_ModBusTcpWorker, &QObject::destroyed, m_Thread, &QThread::quit);

    // 获取QCoreApplication的实例
    QCoreApplication *app = QCoreApplication::instance();
    if(app)
    {
        // 确保在应用程序退出时线程已经结束
        connect(app, &QCoreApplication::aboutToQuit, m_Thread, &QThread::quit);
        connect(m_Thread, &QThread::finished, app, &QCoreApplication::quit);
    }

    connect(this,&FilaPowerForm::sig_SetProNameDevType,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetProNameDevType,Qt::QueuedConnection);
    connect(this,&FilaPowerForm::sig_SetIPPort,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetIPPort,Qt::QueuedConnection);
    connect(this,&FilaPowerForm::sig_SetReadStartAddressAndRegisterCount,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetReadStartAddressAndRegisterCount,Qt::QueuedConnection);
    //connect(this,&FilaPowerForm::sig_SetWriteStartAddressAndRegisterCount,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetWriteStartAddressAndRegisterCount,Qt::QueuedConnection);
    connect(this,&FilaPowerForm::sig_StartLoopReadRegister,m_ModBusTcpWorker,&ModBusTcpWorker::slotStartConnection,Qt::QueuedConnection);
    connect(this,&FilaPowerForm::sig_AddWriteQueue,m_ModBusTcpWorker,&ModBusTcpWorker::slotAddWriteQueue,Qt::QueuedConnection);

    connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_readBoolData,this,&FilaPowerForm::slot_readBoolData,Qt::QueuedConnection);
    connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_readfloatData,this,&FilaPowerForm::slot_readfloatData,Qt::QueuedConnection);
    connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_ConnectionState,this,&FilaPowerForm::slot_ConnectionState,Qt::QueuedConnection);
    connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_WriteDataQueueFinish,this,&FilaPowerForm::slot_WriteDataQueueFinish,Qt::QueuedConnection);

    //线程开始
    m_Thread->start();

    /*******设置子线程*******/
    //设置设备名称和类型ID 这个类被多次实例化区分使用，本次使用不上
    emit sig_SetProNameDevType("017Test",1);
    //emit sig_SetIPPort("192.168.1.100",502);

    QList<int> ReadStartAddressList; //开始地址的列表
    QList<int> ReadRegisterCountList;//开始地址的个数

    // 起始地址和寄存器个数  3为保持寄存器
    ReadStartAddressList  << 0 << 6 << 16 ;
    ReadRegisterCountList << 3 << 2 << 16 ;

    emit sig_SetReadStartAddressAndRegisterCount(ReadStartAddressList,ReadRegisterCountList,3);

    //开始循环读寄存器
    //emit sig_StartLoopReadRegister(true);

    /****************UI 的设置***************************/

    //添加IP验证器
    ui->lineEdit_IP->setValidator(new IPAddressValidator(this));

    this->setFocus();

    ui->dSpinBox_EleCurSet->installEventFilter(this);
    m_fEleCurSet = ui->dSpinBox_EleCurSet->value();

    ui->btn_Fila->setIcon(SwtichOffIcon);
    ui->btn_Fila->setIconSize(QSize(38, 32));
    ui->btn_ReSet->setIcon(SwtichOffIcon);
    ui->btn_ReSet->setIconSize(QSize(38, 32));
    ui->btn_SelfCtrl->setIcon(SwtichOffIcon);
    ui->btn_SelfCtrl->setIconSize(QSize(38, 32));
    ui->btn_EleCurSet->setEnabled(false);

    m_SingleTime = new QTimer(this);
    m_SingleTime->setSingleShot(true);
    connect(m_SingleTime,&QTimer::timeout,this,&FilaPowerForm::timeoutWatchDog_SingleTime);


}

FilaPowerForm::~FilaPowerForm()
{
    delete ui;
}

void FilaPowerForm::setWidgetFocus()
{
    this->setFocus();
}

void FilaPowerForm::setIniFile(QSettings *settings)
{
    m_Settings = settings;
    ui->lineEdit_IP->setText(m_Settings->value("IPSetting/IP","192.168.1.100").toString());
    ui->spinBox_Port->setValue(m_Settings->value("IPSetting/Port",502).toUInt());
}

bool FilaPowerForm::eventFilter(QObject *watched, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *> (event);
        //qDebug()<<watched->objectName();
        if(mouseEvent->button() == Qt::LeftButton)
        {
            if(watched==ui->dSpinBox_EleCurSet )
            {
                qDebug() << "cliecked dSpinBox_EleCurSet";
                bEleCurSetOnlyWrite = true;
            }
        }
    }

    else if(event->type() == QEvent::FocusIn)
    {
        if(watched==ui->dSpinBox_EleCurSet  )
        {
            qDebug() << "FocusIn dSpinBox_EleCurSet";
            bEleCurSetOnlyWrite = true;
            if(m_SingleTime->isActive())
                m_SingleTime->stop();
        }
    }
    else if(event->type() == QEvent::FocusOut)
    {
        if(watched==ui->dSpinBox_EleCurSet  )
        {
            qDebug() << "FocusOut dSpinBox_EleCurSet";
            m_SingleTime->start(1000);
        }
    }

    return QObject::eventFilter(watched,event);
}

void FilaPowerForm::slot_readBoolData(int MsgId, QList<bool> data)
{
    switch (MsgId) {
    case 1:
        if(data.size() != 16)
            return;
        if(data.at(0))
            ui->btn_Fila->setIcon(SwtichOnIcon);
        else
            ui->btn_Fila->setIcon(SwtichOffIcon);

        if(data.at(1))
            ui->btn_ReSet->setIcon(SwtichOnIcon);
        else
            ui->btn_ReSet->setIcon(SwtichOffIcon);

        if(data.at(2))
            ui->btn_SelfCtrl->setIcon(SwtichOnIcon);
        else
            ui->btn_SelfCtrl->setIcon(SwtichOffIcon);

//        ui->btn_Fila->setChecked(data.at(0));
//        ui->btn_ReSet->setChecked(data.at(1));
//        ui->btn_SelfCtrl->setChecked(data.at(2));
        m_BtnStatus = data;//记录按钮状态
        break;

    case 2:
        if(data.size() != 4)
            return;
        ui->btn_PilotLamp_1->setChecked(data.at(0));
        ui->btn_PilotLamp_2->setChecked(data.at(1));
        ui->btn_PilotLamp_3->setChecked(data.at(2));
        ui->btn_PilotLamp_4->setChecked(data.at(3));

        break;

    case 3:
        if(data.size() != 6)
            return;
        ui->btn_FPilotLamp_1->setChecked(data.at(0));
        ui->btn_FPilotLamp_2->setChecked(data.at(1));
        ui->btn_FPilotLamp_3->setChecked(data.at(2));
        ui->btn_FPilotLamp_4->setChecked(data.at(3));
        ui->btn_FPilotLamp_5->setChecked(data.at(4));
        ui->btn_FPilotLamp_6->setChecked(data.at(5));
        break;
    default:
        break;
    }
}

void FilaPowerForm::slot_readfloatData(int MsgId, QList<float> data)
{
    switch (MsgId) {
    case 2:
        if(data.size() != 1)
            return;
        if(!bEleCurSetOnlyWrite && !bEleCurEditing)//可写可读的时候
        {
            ui->dSpinBox_EleCurSet->blockSignals(true);
            m_fEleCurSet = data.at(0);
            ui->dSpinBox_EleCurSet->setValue(m_fEleCurSet);
            ui->dSpinBox_EleCurSet->blockSignals(false);
        }
        break;
    case 3:
        if(data.size() != 8)
            return;

        ui->dSpinBox_1->setValue(data.at(0));
        ui->dSpinBox_2->setValue(data.at(1));
        ui->dSpinBox_3->setValue(data.at(2));
        ui->dSpinBox_4->setValue(data.at(3));
        ui->dSpinBox_5->setValue(data.at(4));
        ui->dSpinBox_6->setValue(data.at(5));
        ui->dSpinBox_7->setValue(data.at(6));
        ui->dSpinBox_8->setValue(data.at(7));
        break;
    default:
        break;
    }
}


void FilaPowerForm::slot_ConnectionState(bool isConnectionState)
{
    bConnectionState = isConnectionState;
    if(bConnectionState)
    {
        emit sig_showMessage("连接成功");
        ui->btn_Link->setText("已连接");
        m_Settings->setValue("IPSetting/IP",ui->lineEdit_IP->text());
        m_Settings->setValue("IPSetting/Port",ui->spinBox_Port->value());
        ui->lineEdit_IP->setEnabled(false);
        ui->spinBox_Port->setEnabled(false);
        ui->btn_EleCurSet->setEnabled(true);
    }
    else
    {
        emit sig_showMessage("连接失败");
        ui->btn_Link->setText("连接");
        ui->lineEdit_IP->setEnabled(true);
        ui->spinBox_Port->setEnabled(true);
        ui->btn_EleCurSet->setEnabled(false);
    }
    ui->btn_PLCLink->setChecked(bConnectionState);
}

void FilaPowerForm::slot_WriteDataQueueFinish()
{
    emit sig_showMessage("写入完成");
}

void FilaPowerForm::timeoutWatchDog_SingleTime()
{
    bEleCurSetOnlyWrite = false;
}

void FilaPowerForm::on_btn_EleCurSet_clicked()
{
    if(!bConnectionState)
        return;

    bEleCurEditing = true;
    QTimer::singleShot(500,[&]()
    {
        bEleCurEditing = false;
    });

    QList<quint16> sendData;
    qDebug() << "sendValue:" << m_fEleCurSet;
    sendData << floatToQuint16( m_fEleCurSet);

    WriteData* writeData = new WriteData(6,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData);
}

void FilaPowerForm::on_dSpinBox_EleCurSet_valueChanged(double arg1)
{
    qDebug() << arg1;
    m_fEleCurSet = static_cast<float>(arg1);
}

void FilaPowerForm::on_btn_Link_clicked()//点击连接
{
    if (!ui->lineEdit_IP->hasAcceptableInput())
    {
        QMessageBox::warning(this, "IP地址提示", "请正确输入IP");
        return;
    }

    if(ui->btn_Link->text() == "连接")
    {
        emit sig_SetIPPort(ui->lineEdit_IP->text(),ui->spinBox_Port->value());
        emit sig_StartLoopReadRegister(true);
    }
    else if(ui->btn_Link->text() == "已连接")
    {
        emit sig_StartLoopReadRegister(false);
    }

}
/*************三个可读可写的按钮***************/
void FilaPowerForm::on_btn_Fila_clicked()
{
    if(!bConnectionState)
        return;
    if(m_BtnStatus.size() != 16)
        return;
    if(m_BtnStatus[0])
        m_BtnStatus[0] = false;
    else
        m_BtnStatus[0] = true;

    QList<quint16> sendData;
    sendData << boolListToQuint16(m_BtnStatus);

    WriteData* writeData = new WriteData(0,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData);
}

void FilaPowerForm::on_btn_ReSet_clicked()
{
    if(!bConnectionState)
        return;
    if(m_BtnStatus.size() != 16)
        return;
    if(m_BtnStatus[1])
        m_BtnStatus[1] = false;
    else
        m_BtnStatus[1] = true;

    QList<quint16> sendData;
    sendData << boolListToQuint16(m_BtnStatus);

    WriteData* writeData = new WriteData(0,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData);

}

void FilaPowerForm::on_btn_SelfCtrl_clicked()
{
    if(!bConnectionState)
        return;
    if(m_BtnStatus.size() != 16)
        return;
    if(m_BtnStatus[2])
        m_BtnStatus[2] = false;
    else
        m_BtnStatus[2] = true;

    QList<quint16> sendData;
    sendData << boolListToQuint16(m_BtnStatus);

    WriteData* writeData = new WriteData(0,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData);

}
/*************三个可读可写的按钮***************/
